package com.gqr.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:ThreadLocalNormalUsage00
 * author:guqingrong
 * Date:2024-05-07 22:06
 * Description: 利用threadLocal,给每个线程分配自己的dateFormat对象,
 * 保证了线程安全,而且高效的利用了内存
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class ThreadLocalNormalUsage05 {

    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException {

        /**
         * 但是当需求变成了1000个,那么必然要用线程池(否则消耗内存太多)
         * 有个弊端 创建了 SimpleDateFormat 1000次然后又销毁掉
         * 可以就创建一次 每次都调用这同一个实例 看ThreadLocalNormalUsage03
         */
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    String date = new ThreadLocalNormalUsage05().date(finalI);
                    System.out.println(date);
                }
            });
        }
        threadPool.shutdown();

    }

    public String date(int seconds) {
        // 参数的单位是毫秒,从1970年01月01日 00:00:00 GMT计时
        Date date = new Date(1000L * seconds);
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat dateFormat = ThreadSafeFormatter.dateFormatThreadLocal.get();
        return dateFormat.format(date);
    }
}

class ThreadSafeFormatter {
    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        }
    };

    // lambda表达式写法
    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal2 =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
}
